package com.example.fresh_market.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;

import com.android.volley.Request;
import com.bumptech.glide.request.RequestOptions;
import com.example.fresh_market.adapter.CateSpinnerAdapter;
import com.example.fresh_market.databinding.ActivityProdEditBinding;
import com.example.fresh_market.entity.ProdCate;
import com.example.fresh_market.entity.Product;
import com.example.fresh_market.request.ApiResponse;
import com.example.fresh_market.request.PageResult;
import com.example.fresh_market.utils.HttpUtil;
import com.example.fresh_market.utils.ToastUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class ProductEditActivity extends AppCompatActivity {

    private ActivityProdEditBinding binding;
    private Context mContext;
    private CateSpinnerAdapter adapter;
    private Spinner spinner;
    private Long cateId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityProdEditBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        mContext = this;
        initCategory();
        String json = getIntent().getStringExtra("product");
        int method = Request.Method.POST;
        if (StringUtils.isNotBlank(json)) {
            Product product = new Gson().fromJson(json, Product.class);
            cateId = product.getCateId();
            binding.prodIdTextView.setText(String.format("%s", product.getId()));
            binding.prodNameEditText.setText(product.getName());
            binding.priceEditText.setText(product.getPrice());
            binding.infoEditText.setText(product.getInfo());
            binding.isShowCheckBox.setChecked(product.getIsShow());
            if (StringUtils.isNotBlank(product.getImage())) {
                HttpUtil.loadImage(binding.prodImageView, product.getImage(), new RequestOptions());
            }
            method = Request.Method.PUT;
        }
        binding.prodImageView.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, 777);
        });
        final int finalMethod = method;
        binding.saveButton.setOnClickListener(v -> {
            // 获取图片
            Drawable drawable = binding.prodImageView.getDrawable();
            String image = null;
            if (drawable instanceof BitmapDrawable) {
                Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
                image = Base64.getEncoder().encodeToString(stream.toByteArray());
            }
            ProdCate prodCate = adapter.getSelectedCate();
            if (prodCate == null) {
                ToastUtil.showToast(mContext, "请选择分类");
                return;
            }
            Product product = Product.builder()
                    .price(binding.priceEditText.getText().toString())
                    .image(image)
                    .cateId(prodCate.getId())
                    .name(binding.prodNameEditText.getText().toString())
                    .info(binding.infoEditText.getText().toString())
                    .isShow(binding.isShowCheckBox.isChecked())
                    .build();
            String id = binding.prodIdTextView.getText().toString();
            if (StringUtils.isNotBlank(id)) {
                product.setId(Long.valueOf(id));
            }
            saveOrUpdateProduct(finalMethod, product);
        });
    }

    public void initCategory() {
        adapter = getSpinnerAdapter();
        HttpUtil.get(mContext, "/admin/product/cate?page=1&size=100000", response -> {
            ApiResponse<PageResult<ProdCate>> apiResponse = new Gson().fromJson(response,
                    new TypeToken<ApiResponse<PageResult<ProdCate>>>() {
                    }.getType());
            if (apiResponse.getCode() == 200) {
                List<ProdCate> cateList = apiResponse.getData().getList();
                adapter.addAll(cateList);
                adapter.notifyDataSetChanged();
                for (int i = 0; i < cateList.size(); i++) {
                    if (cateList.get(i).getId().equals(cateId)) {
                        spinner.setSelection(i);
                        break;
                    }
                }
            }
        });
    }

    private CateSpinnerAdapter getSpinnerAdapter() {
        spinner = binding.prodCategorySpinner;
        CateSpinnerAdapter spinnerAdapter = new CateSpinnerAdapter(mContext, new ArrayList<>());
        spinner.setAdapter(spinnerAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ProdCate prodCate = (ProdCate) parent.getItemAtPosition(position);
                spinnerAdapter.setSelectedCate(prodCate);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        return spinnerAdapter;
    }

    private void saveOrUpdateProduct(int method, Product product) {
        Gson gson = new Gson();
        HttpUtil.sendJsonRequest(mContext, method, "/admin/product", gson.toJson(product), response -> {
            ApiResponse apiResponse = gson.fromJson(response.toString(), ApiResponse.class);
            if (apiResponse.getCode() == 200) {
                ToastUtil.showToast(mContext, "保存成功");
                Intent intent = new Intent(mContext, ProductActivity.class);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 777 && data != null) {
            Uri imageUri = data.getData();
            if (imageUri != null) {
                try (InputStream inputStream = getContentResolver().openInputStream(imageUri)) {
                    if (inputStream != null) {
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        binding.prodImageView.setImageBitmap(bitmap);
                    }
                } catch (Exception e) {
                    e.printStackTrace(System.err);
                }
            }
        }
    }
}
